package com.jcbase.core.util;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

import org.apache.log4j.Logger;

import com.jcbase.core.pojo.User;
import com.jcbase.model.SysConfig;
import com.jcbase.model.SysConfigAd;

public class AdUtil {

	
	private static Logger log = Logger.getLogger(AdUtil.class);
	 private String host, url, adminName, adminPassword,Dc;  
	 public LdapContext ctx  ;    
	    /** 
	     * 初始化ldap 
	     */  
	    @SuppressWarnings({ "unchecked", "rawtypes" })  
	    public boolean initLdap() {  
	    	
	    	SysConfigAd sysConfigAd = SysConfigAd.dao.findFirst("select * from sys_config_ad");
	        // ad服务器  
	        this.host =sysConfigAd.getAdHost(); // AD服务器  
	        this.url = new String("ldap://" + host);// 默认端口为80的可以不用填写，其他端口需要填写，如ldap://xxx.com:8080  
	        this.adminName =sysConfigAd.getAdUser();// 注意用户名的写法：User@domain.com  
	        this.adminPassword = sysConfigAd.getAdPwd();  
	        this.Dc = sysConfigAd.getAdDc();  
	        Hashtable HashEnv = new Hashtable();  
	        HashEnv.put(Context.SECURITY_AUTHENTICATION, sysConfigAd.getAdSafeLevel()); // LDAP访问安全级别  
	        HashEnv.put(Context.SECURITY_PRINCIPAL, adminName); // AD User  
	        HashEnv.put(Context.SECURITY_CREDENTIALS, adminPassword); // AD Password  
	        HashEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // LDAP工厂类  
	        HashEnv.put(Context.PROVIDER_URL, url);  
	        try {  
	            ctx = new InitialLdapContext(HashEnv,null);  
	            log.info("初始化ldap成功！");    
	            return true;        
	        } catch (NamingException e) {  
	            e.printStackTrace();  
	            System.err.println("Throw Exception : " + e); 
	            return false;    
	        }  
	    }  
	  
	    /** 
	     * 关闭ldap 
	     */  
	    public void closeLdap() {  
	        try {  
	            this.ctx.close();  
	        } catch (NamingException e) {  
	            e.printStackTrace();  
	        }  
	    }  
	  
	   
	    /** 
	     *  获取所有域用户信息并封装成User对象
	     * @param type organizationalUnit:组织架构 group：用户组 user|person：用户 
	     * @param name 
	     * @return 
	     */  
	    public List<User> GetADInfo(String DC, LdapContext ctx) {  
	    		List<User> userList = new ArrayList<User>(); 
	    	  SearchControls searchCtls = new SearchControls();  
              searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);  
              String searchFilter = "(objectClass=User)";  
//              String searchBase = "DC=test,DC=com";  
              String searchBase = DC;  
              String attributeNames[] = { "memberOf","sAMAccountName","description"};// 定制返回属性  
              searchCtls.setReturningAttributes(attributeNames);
              NamingEnumeration<SearchResult> answer;
			try {
				answer = ctx.search(searchBase, searchFilter,searchCtls);
  			while (answer.hasMoreElements()) {
  				SearchResult sr = (SearchResult) answer.next();
  				 String dn = sr.getName();  
                 System.out.println("dn=" +dn);  
  				Attributes attrs = sr.getAttributes();
  				if(attrs!=null){
  					User user = new User();
  					 for (NamingEnumeration<?> ne = attrs.getAll(); ne.hasMore();) {  
  						  Attribute Attr = (Attribute) ne.next();// 得到下一个属性  
  						 System.out.println("属性名："+ Attr.getID().toString());  
  						 if("sAMAccountName".equals(Attr.getID().toString())){
  							NamingEnumeration<?> e = Attr.getAll();
	 	                      // 读取属性值  
	 	 	  				 while(e.hasMore()){
	 	 	  					String value = e.next().toString();
	 	 	  					user.setUser(value);
	 	 	                    System.out.println("属性值："+value);  
	 	 	                    break;
	 	 	  				 }
  						 }
  						if("memberOf".equals(Attr.getID().toString())){
  							NamingEnumeration<?> e = Attr.getAll();
	 	                      // 读取属性值  
	 	 	  				 while(e.hasMore()){
	 	 	  					String value = e.next().toString();
	 	 	  					String[] group = value.split(",");
	 	 	  					if(group!=null&&group.length>0){
	 	 	  					value = group[0].split("=")[1];
	 	 	  					user.setGroup(value);
	 	 	                    System.out.println("属性值："+value);  
	 	 	                    break;
	 	 	  					}else{
	 	 	  						break;
	 	 	  					}
	 	 	  				 }
  						 }
  						if("description".equals(Attr.getID().toString())){
  							NamingEnumeration<?> e = Attr.getAll();
	 	                      // 读取属性值  
	 	 	  				 while(e.hasMore()){
	 	 	  					String value = e.next().toString();
	 	 	  					user.setCommon(value);
	 	 	                    System.out.println("属性值："+value);  
	 	 	                    break;
	 	 	  				 }
  						 }
  					 }
  					userList.add(user);
  				}
  			  
  			}
  			 ctx.close();  
			}catch (NamingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}   
           return userList;
          }  
	      
	  
	  
	    public static void main(String args[]) {  
	        // 实例化  
	    	AdUtil ad = new AdUtil();  
	        ad.initLdap();  
	        List<User> user = ad.GetADInfo("DC=test,DC=com",ad.ctx);// 查找用户  
	        
	      System.out.println(user.size());
	    }  
	}  
